package kr.ac.hufs;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.Socket;

import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToggleButton;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JInternalFrame;
import javax.swing.JTree;

//import net.miginfocom.swing.MigLayout;
import javax.swing.JSplitPane;
import javax.swing.JToolBar;
import javax.swing.JEditorPane;
import javax.swing.SwingConstants;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.TextField;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.border.BevelBorder;
import javax.swing.UIManager;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.JPopupMenu;
import java.awt.Component;
import javax.swing.JRadioButton;
import javax.swing.border.SoftBevelBorder;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.TextArea;
import java.awt.Label;
import java.awt.Button;
import javax.swing.JProgressBar;
import javax.swing.border.MatteBorder;
import javax.swing.JFileChooser;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileView;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.JTextArea;
import javax.swing.JList;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ContainerAdapter;
import java.awt.event.ContainerEvent;

public class FTP_Client extends JFrame implements TreeSelectionListener {
	protected static final TreeSelectionListener FTP_Clent = null;

	protected static final TreeSelectionListener FTP_Client = null;

	static main main = new main();

	int flag;
	String ip;
	int requestNum = 0;
	private JPanel IPPane;
	UserInfoProvider uip;
	table server_table;
	boolean passiveFlag = true;

	protected FileSystemModel model;
	protected JTree tree;
	protected JTable table;
	protected JLabel status;
	protected JMenuItem exit;
	protected FileFolder dir;
	protected DefaultTableModel model3;
	protected FileSystemModel model2;
	protected JTree tree2;
	protected JTable table2;
	protected JLabel status2;
	protected JMenuItem exit2;
	protected FileFolder dir2;
	boolean mode = true;

	/**
	 * Launch the application.
	 * 
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		// uip = new UserInfoProvider();

		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {

					FTP_Client frame = new FTP_Client();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});

	}

	/**
	 * Create the frame.
	 * 
	 * @throws IOException
	 */
	public FTP_Client() throws IOException {
		setTitle("Perpect FTP_Client");

		/* user info initialize */
		uip = new UserInfoProvider();

		var.CURRENT_STATE = var.USER_COMMAND;
		var.ACTIVE_MODE = var.OFF;
		var.ACTIVE_PORT_NUM = 2000;
		var.DEBUG_MODE = var.ON;
		var.BINARY_MODE = var.ON;
		var.ACTIVE_MODE = var.OFF;
		// String tmp;
		/* user info initialize */
		/* GUI init */
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 892, 644);
		IPPane = new JPanel();
		IPPane.setBorder(new SoftBevelBorder(BevelBorder.RAISED, null, null,
				null, null));
		setContentPane(IPPane);

		JPanel Log_panel = new JPanel();
		Log_panel.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));

		Label label = new Label("LOG");
		Log_panel.add(label);

		JPanel mode_panel = new JPanel();
		FlowLayout fl_mode_panel = (FlowLayout) mode_panel.getLayout();
		fl_mode_panel.setHgap(3);
		mode_panel.setBorder(new SoftBevelBorder(BevelBorder.RAISED, null,
				null, null, null));

		final TextArea textArea = new TextArea();
		textArea.setRows(6);
		textArea.setColumns(110);
		Log_panel.add(textArea);		

		JPanel panel = new JPanel();
		panel.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));

		JLabel serverIp = new JLabel("\uD638\uC2A4\uD2B8(H):");
		panel.add(serverIp);

		final TextField textField = new TextField();
		textField.setColumns(15);
		panel.add(textField);
		FileView view;
		
		JPanel client_panel = new JPanel();

		client_panel
				.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));

		final JPanel server_panel = new JPanel();
		server_panel.setLayout(null);
		server_panel
				.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));

		JPanel get_panel = new JPanel();
		get_panel.setBorder(new SoftBevelBorder(BevelBorder.RAISED, null, null,
				null, null));

		JPanel put_panel = new JPanel();
		put_panel.setBorder(new SoftBevelBorder(BevelBorder.RAISED, null, null,
				null, null));

		JPanel Copy_right = new JPanel();
		Copy_right.setBorder(new SoftBevelBorder(BevelBorder.RAISED, null,
				null, null, null));

		JLabel lblNewLabel_1 = new JLabel(
				"Network Programming Last Project Team  :  \uAE40\uC9C0\uD6C8, \uAE40\uB450\uD615, \uC591\uC724\uC2DD, \uAE40\uD0DC\uC601 ");
		Copy_right.add(lblNewLabel_1);

		Button button_1 = new Button("Put");
		put_panel.add(button_1);

		Button button = new Button("Get");

		get_panel.add(button);

		JLabel user = new JLabel("\uC0AC\uC6A9\uC790\uBA85(U):");
		panel.add(user);

		final TextField textField_1 = new TextField();
		textField_1.setColumns(10);
		panel.add(textField_1);

		JLabel pass = new JLabel("\uBE44\uBC00\uBC88\uD638(W):");
		panel.add(pass);

		final TextField textField_2 = new TextField();
		textField_2.setColumns(10);
		textField_2.setEchoChar('*');
		panel.add(textField_2);

		JLabel port = new JLabel("\uD3EC\uD2B8(P):");
		panel.add(port);
		// tmp = textField.getText();
		// uip.setPortNum(Integer.parseInt(tmp));

		JRadioButton rdbtnPassiveMode = new JRadioButton("Passive Mode");

		// server_panel.add(splitPane_1);

		client_panel.setLayout(null);

		final TextField textField_3 = new TextField();
		textField_3.setColumns(5);
		panel.add(textField_3);

		JButton btnNewButton = new JButton("\uC5F0\uACB0(Q)");
		btnNewButton.setToolTipText("");
		panel.add(btnNewButton);
	
		dir = new FileFolder("" + System.getProperty("user.dir") + "", ""
				+ System.getProperty("user.dir") + "");
		model = new FileSystemModel(dir);

		tree = new JTree(model);

		tree.addTreeSelectionListener(this);

		table = new JTable(model);
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {

				int row = table.getSelectedRow();
				uip.setCli_fileName((String) table.getValueAt(row, 0));

				System.out.println(uip.getCli_fileName());

				// fileName = table.getName();

				// System.out.println(table.getSelectedColumn());

			}
		});

		JTableHeader header = table.getTableHeader();
		header.setPreferredSize(new Dimension(20, 20));
		table.setRowHeight(20);

		JSplitPane splitPane = new JSplitPane();
		splitPane.setResizeWeight(0.3);
		splitPane.setBounds(12, 10, 375, 307);
		splitPane.setLeftComponent(new JScrollPane(tree));
		splitPane.setRightComponent(new JScrollPane(table));

		client_panel.add(splitPane);

		// dir2 = new FileFolder(".",".");
		// model2 = new FileSystemModel(dir2);

		// server_panel.add(splitPane_1);

		btnNewButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				try {

					uip.setIPAddr(textField.getText());
					uip.setID(textField_1.getText());
					uip.setPWD(textField_2.getText());
					uip.setPortNum(textField_3.getText());
					// uip.setIPAddr(textField_3.getText());

					requestNum = var.OPEN;
					main.main(requestNum, uip, textArea);

					DefaultMutableTreeNode root = new DefaultMutableTreeNode(
							"/");
					for (int k = 0; k < uip.directory.length; k++) {
						if (uip.directory[k] == null)
							break;
						// System.out.println(uip.directory[k]);
						DefaultMutableTreeNode tree1 = new DefaultMutableTreeNode(
								uip.directory[k]);
						tree1.add(new DefaultMutableTreeNode(null));
						root.add(tree1);

					}

					JSplitPane splitPane_1 = new JSplitPane();
					splitPane_1.setResizeWeight(0.3);
					splitPane_1.setBounds(12, 10, 378, 307);
					server_panel.add(splitPane_1);

					tree2 = new JTree(root);
					JScrollPane scrollpane_tree = new JScrollPane(tree2);
					tree2.addTreeSelectionListener(FTP_Client);

					server_table = new table();
					model3 = server_table.maketable(uip);					
					table2 = new JTable(model3);					
					table2.updateUI();
					splitPane_1.setLeftComponent(new JScrollPane(tree2));
					splitPane_1.setRightComponent(new JScrollPane(table2));		
	
					tree2.addMouseListener(new MouseAdapter() {					  
						  @Override public void mouseClicked(MouseEvent arg0) {
							  //model3.setNumRows(0);							 
						       Object o = tree2.getLastSelectedPathComponent();
						       uip.setCdName(o.toString());
						       System.out.println(uip.getCdName());
						       
						     
						        requestNum = var.CD;
						        var.CURRENT_STATE = var.USER_COMMAND;
						        try {
									main.main(requestNum, uip, textArea);
									
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
						        					    
						        if (o instanceof DefaultMutableTreeNode) {
						         
						         DefaultMutableTreeNode root2 = (DefaultMutableTreeNode) o;
						         for (int k = 0; k < uip.directory.length; k++) {
						          if (uip.directory[k] == null){						        
							          break;
						          }
						        
						          // System.out.println(uip.directory[k]);
						          DefaultMutableTreeNode tree2 = new DefaultMutableTreeNode(
						            uip.directory[k]);
						          tree2.add(new DefaultMutableTreeNode(null));
						          root2.add(tree2);											          
						         }						        
						         
						        }
						        
						        model3 = server_table.maketable(uip);
						        model3.fireTableDataChanged();
						      }
						     });
	
					table2.addMouseListener(new MouseAdapter() {
						@Override
						public void mouseClicked(MouseEvent arg0) {

							int row = table2.getSelectedRow();
							uip.setSrv_filename((String) table2.getValueAt(row,0));
							System.out.println(uip.getSrv_filename());
						}
					});
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});

		button_1.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {

				var.CURRENT_STATE = var.USER_COMMAND;
				requestNum = var.PUT;

				try {
					main.main(requestNum, uip, textArea);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});

		button.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {

				var.CURRENT_STATE = var.USER_COMMAND;
				requestNum = var.GET;

				try {
					main.main(requestNum, uip, textArea);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		rdbtnPassiveMode.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {

				if (passiveFlag == true) {
					textArea.append("System : Active Mode On\n");
					passiveFlag = false;
				} else if (passiveFlag == false) {
					textArea.append("System : Passive Mode On\n");
					passiveFlag = true;
				}
				requestNum = var.PASSIVE;
				try {
					main.main(requestNum, uip, textArea);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});

		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new SoftBevelBorder(BevelBorder.RAISED, null, null,
				null, null));

		JPanel panel_2 = new JPanel();

		JPanel panel_3 = new JPanel();
		panel_3.setBorder(new SoftBevelBorder(BevelBorder.RAISED, null, null,
				null, null));
		GroupLayout gl_IPPane = new GroupLayout(IPPane);
		gl_IPPane
				.setHorizontalGroup(gl_IPPane
						.createParallelGroup(Alignment.TRAILING)
						.addGroup(
								gl_IPPane
										.createSequentialGroup()
										.addGroup(
												gl_IPPane
														.createParallelGroup(
																Alignment.TRAILING)
														.addComponent(
																panel,
																GroupLayout.PREFERRED_SIZE,
																865,
																GroupLayout.PREFERRED_SIZE)
														.addGroup(
																gl_IPPane
																		.createSequentialGroup()
																		.addContainerGap()
																		.addComponent(
																				panel_2,
																				GroupLayout.PREFERRED_SIZE,
																				584,
																				GroupLayout.PREFERRED_SIZE)
																		.addGap(8)
																		.addComponent(
																				panel_1,
																				GroupLayout.PREFERRED_SIZE,
																				124,
																				GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				ComponentPlacement.RELATED)
																		.addComponent(
																				mode_panel,
																				GroupLayout.PREFERRED_SIZE,
																				130,
																				GroupLayout.PREFERRED_SIZE))
														.addGroup(
																gl_IPPane
																		.createSequentialGroup()
																		.addGap(3)
																		.addGroup(
																				gl_IPPane
																						.createParallelGroup(
																								Alignment.LEADING)
																						.addGroup(
																								gl_IPPane
																										.createSequentialGroup()
																										.addComponent(
																												Copy_right,
																												GroupLayout.PREFERRED_SIZE,
																												463,
																												GroupLayout.PREFERRED_SIZE)
																										.addPreferredGap(
																												ComponentPlacement.RELATED)
																										.addComponent(
																												panel_3,
																												GroupLayout.PREFERRED_SIZE,
																												392,
																												GroupLayout.PREFERRED_SIZE))
																						.addGroup(
																								gl_IPPane
																										.createSequentialGroup()
																										.addComponent(
																												client_panel,
																												GroupLayout.PREFERRED_SIZE,
																												402,
																												GroupLayout.PREFERRED_SIZE)
																										.addPreferredGap(
																												ComponentPlacement.RELATED,
																												8,
																												Short.MAX_VALUE)
																										.addGroup(
																												gl_IPPane
																														.createParallelGroup(
																																Alignment.TRAILING)
																														.addComponent(
																																get_panel,
																																GroupLayout.PREFERRED_SIZE,
																																43,
																																GroupLayout.PREFERRED_SIZE)
																														.addComponent(
																																put_panel,
																																GroupLayout.PREFERRED_SIZE,
																																43,
																																GroupLayout.PREFERRED_SIZE))
																										.addPreferredGap(
																												ComponentPlacement.RELATED)
																										.addComponent(
																												server_panel,
																												GroupLayout.PREFERRED_SIZE,
																												402,
																												GroupLayout.PREFERRED_SIZE))
																						.addComponent(
																								Log_panel,
																								GroupLayout.DEFAULT_SIZE,
																								862,
																								Short.MAX_VALUE))))
										.addContainerGap()));
		gl_IPPane
				.setVerticalGroup(gl_IPPane
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								gl_IPPane
										.createSequentialGroup()
										.addComponent(panel,
												GroupLayout.PREFERRED_SIZE,
												GroupLayout.DEFAULT_SIZE,
												GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												ComponentPlacement.RELATED)
										.addGroup(
												gl_IPPane
														.createParallelGroup(
																Alignment.LEADING)
														.addComponent(
																mode_panel,
																Alignment.TRAILING,
																GroupLayout.DEFAULT_SIZE,
																39,
																Short.MAX_VALUE)
														.addComponent(
																panel_1,
																Alignment.TRAILING,
																GroupLayout.PREFERRED_SIZE,
																GroupLayout.DEFAULT_SIZE,
																Short.MAX_VALUE)
														.addComponent(
																panel_2,
																GroupLayout.PREFERRED_SIZE,
																53,
																GroupLayout.PREFERRED_SIZE))
										.addPreferredGap(
												ComponentPlacement.RELATED)
										.addComponent(Log_panel,
												GroupLayout.PREFERRED_SIZE,
												GroupLayout.DEFAULT_SIZE,
												GroupLayout.PREFERRED_SIZE)
										.addGroup(
												gl_IPPane
														.createParallelGroup(
																Alignment.LEADING)
														.addGroup(
																gl_IPPane
																		.createSequentialGroup()
																		.addPreferredGap(
																				ComponentPlacement.RELATED)
																		.addGroup(
																				gl_IPPane
																						.createParallelGroup(
																								Alignment.LEADING)
																						.addComponent(
																								client_panel,
																								GroupLayout.PREFERRED_SIZE,
																								327,
																								GroupLayout.PREFERRED_SIZE)
																						.addComponent(
																								server_panel,
																								GroupLayout.PREFERRED_SIZE,
																								327,
																								GroupLayout.PREFERRED_SIZE)))
														.addGroup(
																gl_IPPane
																		.createSequentialGroup()
																		.addGap(61)
																		.addComponent(
																				get_panel,
																				GroupLayout.PREFERRED_SIZE,
																				37,
																				GroupLayout.PREFERRED_SIZE)
																		.addGap(151)
																		.addComponent(
																				put_panel,
																				GroupLayout.PREFERRED_SIZE,
																				36,
																				GroupLayout.PREFERRED_SIZE)))
										.addPreferredGap(
												ComponentPlacement.RELATED)
										.addGroup(
												gl_IPPane
														.createParallelGroup(
																Alignment.LEADING)
														.addComponent(
																Copy_right,
																GroupLayout.PREFERRED_SIZE,
																30,
																GroupLayout.PREFERRED_SIZE)
														.addComponent(
																panel_3,
																GroupLayout.PREFERRED_SIZE,
																29,
																GroupLayout.PREFERRED_SIZE))
										.addContainerGap()));
		panel_3.setLayout(null);

		JLabel lblProfessorByHong = new JLabel("Professor By Jin Pyo Hong");
		lblProfessorByHong.setBounds(124, 9, 177, 15);
		panel_3.add(lblProfessorByHong);
		panel_2.setLayout(null);

		JProgressBar Bar = new JProgressBar();
		Bar.setBounds(0, 0, 584, 53);
		Bar.setStringPainted(true);
		panel_2.add(Bar);

		// Bar.setMaximum()

		JRadioButton rdbtnBinaryMode = new JRadioButton("Binary Mode");
		rdbtnBinaryMode.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {

				if (mode == true) {
					textArea.append("System : ASCII Mode On\n");
					var.BINARY_MODE = var.OFF;
					mode = false;
				} else {
					textArea.append("System : Binary Mode On\n");
					var.BINARY_MODE = var.ON;
					mode = true;
				}
			}
		});
		rdbtnBinaryMode.setSelected(true);
		panel_1.add(rdbtnBinaryMode);

		rdbtnPassiveMode.setMnemonic('2');
		rdbtnPassiveMode.setSelected(true);
		rdbtnPassiveMode.setHorizontalAlignment(SwingConstants.CENTER);
		mode_panel.add(rdbtnPassiveMode);
		IPPane.setLayout(gl_IPPane);

	}

	private static void addPopup(Component component, final JPopupMenu popup) {
		component.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}

			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}

			private void showMenu(MouseEvent e) {
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}
	@Override
	public void valueChanged(TreeSelectionEvent e) {
		Object o = tree.getLastSelectedPathComponent();	

		if (o instanceof FileFolder) {
			FileFolder current = (FileFolder) o;
			model.setCurrent(current);
			table.updateUI();
			// status.setText(current.getPath());
		}	

	}
}
